﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.Xml;

namespace StuMana.UI
{
    public partial class Student1 : Office2007Form
    {
         // export excel
        Services.ExcelInterface excel = null;
        
        // datagridview parameters
        List<string>[] list;
        string[] columnName;
        string query;
        string[] columnNameReal;
        int page;
        int maxpage;
        static int rowperpage;

        #region Students
        /// <summary>
        /// // serrvices
        /// </summary>
        private Services.student newstudent = new Services.student();
        private Services.SL025M rfid_reader = new Services.SL025M();
        public Services.COM connect;
        private Services.DataviewService dataview = new Services.DataviewService();

        //timer catch byteArray
        private byte[] serial_buff = new byte[40];

        private int action = 0;

        Label pages = new Label();
       

        // studen initial values
        private void Student_initial()
        {
            pages.Text = "1";

            columnName = new string[] { "TagID", "Name", "BirthDay", "Gender", "Class","Account","LateTime" };
            columnNameReal = new string[] { "TagID", "Name", "BirthDay", "Gender", "Class", "Account", "LateTime" };
            query = "SELECT TagID, Name, BirthDay, Gender, Class, Account, LateTime FROM studentinfo";
            rowperpage = 10;
            page = 0;


            // button disable
            btnXUpdate.Enabled = false;
            btnXWriteTag.Enabled = false;
            btnXDelete.Enabled = false;
            //bt_next.Enabled = true;
            //bt_previous.Enabled = true;

            // combobox initial
            cmbExGender.Items.Add("Nam");
            cmbExGender.Items.Add("Nu");
            cmbExGender.SelectedIndex = 0;
            
            cmbExClass.Items.Add("10A1");
            cmbExClass.Items.Add("10A2");
            cmbExClass.Items.Add("10A3");
            cmbExClass.Items.Add("11A1");
            cmbExClass.Items.Add("11A2");
            cmbExClass.Items.Add("11A3");
            cmbExClass.Items.Add("12A1");
            cmbExClass.Items.Add("12A2");
            cmbExClass.Items.Add("12A3");
            cmbExClass.Items.Add("12A4");
            cmbExClass.SelectedIndex = 0;

            for (int i =1; i < 32; i++)
            {
                cmbExDay.Items.Add(i.ToString());
            }
            cmbExDay.SelectedIndex = 0;

            for (int i = 1; i < 13; i++)
            {
                cmbExMonth.Items.Add(i.ToString());
            }
            cmbExMonth.SelectedIndex = 0;

            cmbExLastTime.Items.Add("NONE");
            cmbExLastTime.Items.Add("07:00:00");
            cmbExLastTime.Items.Add("07:15:00");
            cmbExLastTime.Items.Add("07:30:00");
            cmbExLastTime.Items.Add("07:45:00");
            cmbExLastTime.SelectedIndex = 0;

            dataview.setData(rowperpage, columnName, columnNameReal);
           // dataview.DataOnDataGridViewInitial(dataGridView1,query,2,-1,pages);
            dataview.DataOnDataGridViewInitial(dgvExDanhSach, query, 2, -1, pages);

            int w = dgvExDanhSach.Size.Width;
            int widthC = ((int)w / dgvExDanhSach.Columns.Count);
            if (co == true)
            {
                for (int i = 0; i < dgvExDanhSach.Columns.Count; i++)
                {
                    dgvExDanhSach.Columns[i].Width = widthC;
                }


            }
            initial_button();

        }

        // tagID text changed
        private void txtTagID_TextChanged(object sender, EventArgs e)
        {
            switch (action)
            {
                // query and show on datagridview
                case 1:
                    tb_tagid_query();
                    break;

                //remove last input character
                case 2:
                    remove_character();
                    break;

                //not acting for datagridview click
                case 3:
                    break;

                default:
                    tb_tagid_query();
                    break;
            }
        }
        

        //handle key down to determine whether accepted key
        private void txtTagID_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyValue >= 48 && e.KeyValue <= 57) || (e.KeyValue >= 96 && e.KeyValue <= 105))
            {
                action = 1;
                // ts_label.Text = "None";
                labelItemStatus.Text = "None";
            }
            else if (e.KeyValue == 46)
            {
                action = 1;
            }
            else if (e.KeyValue != 8)
            {
                action = 2;
                //ts_label.Text = "Number only";
                labelItemStatus.Text = "Number only";
            }        
        }
    

       // tagid query incase text changed
        private void tb_tagid_query()
        {
            pages.Text = "1";
           // if (tb_tagid.Text == ""){
            if (txtTagID.Text == "")
            {
                    FormReset();
                    query = "SELECT * FROM studentinfo";
            }
            else
                  
                query = "SELECT * FROM studentinfo WHERE TagID LIKE '" + txtTagID.Text + "%'";

            dataview.DataOnDataGridViewInitial(dgvExDanhSach, query, 2, -1, pages);
            initial_button();
            
        }

        // remove the last character input
        private void remove_character()
        {
            int temp = txtTagID.SelectionStart;
            if (temp > 0)
            {
                txtTagID.Text = txtTagID.Text.Remove(temp - 1, 1);
                txtTagID.SelectionStart = temp - 1;
            }       
        }        
        
        // input year
        private void txtXYear_TextChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < txtXYear.Text.Length; i++)
            {
                if (txtXYear.Text[i] < 48 || txtXYear.Text[i] > 57)
                {
                    txtXYear.Text = txtXYear.Text.Substring(0, txtXYear.Text.Length - 1);
                    txtXYear.SelectionStart = txtXYear.Text.Length;
                    labelItemStatus.Text = "Number only";
                    //  MessageBox.Show("TagID chi bao gom so");
                }
                else
                    labelItemStatus.Text = "None";
            }  
        }
       

      

        // Initial COM connecting
        public void InitialConnect(StuMana.Services.COM conn)
        {
            connect = conn;
            rfid_reader.conn = conn.serialPort;
        }

        //set status to ts_connect
        public void setStatus(string stt)
        {
            labelItemConnect.Text = stt;
        }

       

        // infor reset
        private void FormReset()
        {
            btnXWriteTag.Enabled = false;
            btnXInsert.Enabled = true;
            btnXDelete.Enabled = false;
            btnXUpdate.Enabled = false;


            txtTagID.Enabled = true;
            txtXName.Enabled = true;
            cmbExClass.Enabled = true;
            cmbExDay.Enabled = true;
            cmbExGender.Enabled = true;
            cmbExMonth.Enabled = true;
            txtXYear.Enabled = true;
            txtXAccount.Enabled = true;   
 
            txtXName.Text = "";
            cmbExClass.SelectedIndex = 0;
            cmbExDay.SelectedIndex = 0;
            cmbExGender.SelectedIndex = 0;
            cmbExMonth.SelectedIndex = 0;
            txtXYear.Text = "";
            txtXAccount.Text = "0";
            txtTagID.Text = "";
        }

       

        // datagrid view selected row
        private void datagrid_selectedrow(string TagID)
        {
            int rowNumber = dgvExDanhSach.RowCount;
            for (int j = 0; j < rowNumber; j++)
            {
                if (dgvExDanhSach.Rows[j].Cells[0].Value.ToString() == TagID)
                {
                    dgvExDanhSach.CurrentRow.Selected = false;
                    dgvExDanhSach.Rows[j].Selected = true;
                    break;
                }
            }
        }

       

       

        // assign value from form to student attributes
        private void student_GetInfo()
        {
            newstudent.TagID = int.Parse(txtTagID.Text);
            newstudent.Name = txtXName.Text;
            if (txtXYear.Text != "")
                newstudent.Birthday = txtXYear.Text + "-" + cmbExMonth.SelectedItem.ToString() + "-" + cmbExDay.SelectedItem.ToString();
            else
                throw new Exception("Please input year of birth (maybe input the 2 last number)");
            newstudent.Gender = cmbExGender.SelectedItem.ToString();
            newstudent.Class = cmbExClass.SelectedItem.ToString();
            
            if (txtXAccount.Text != "")
                newstudent.Account = int.Parse(txtXAccount.Text);

            if (int.Parse(txtXAccount.Text) >= 2147483647)
                throw new Exception("The number input so large");
            else newstudent.Account = int.Parse(txtXAccount.Text);

            if (cmbExLastTime.Text != "NONE")
                newstudent.LateTime = cmbExLastTime.Text;
            else
                newstudent.LateTime = null;
                

            
            // out of area
            newstudent.InOut = false;
        }

      
        
        private void initial_button()
        {
            page = dataview.GetPage();
            //maxpage = dataview.GetMaxPage();
            //if (page == maxpage)
            //    bt_next.Enabled = false;
            //bt_previous.Enabled = false;
        }

        #endregion
        private bool flag = false;
        private bool co = false;
        private Font fontForAll = null;
        private StyleManager managerStyle = new DevComponents.DotNetBar.StyleManager();



        public void ReadSetting()
        {
            XmlReader reader = XmlReader.Create("Settings.xml");
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element
                && reader.Name == "font")
                {
                    string name = reader.GetAttribute(0).ToString();
                    string style = reader.GetAttribute(1).ToString();
                    float size = float.Parse(reader.GetAttribute(2).ToString());



                    if (style == "Bold")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Italic")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Regular")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Strikeout")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Strikeout, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Underline")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        reader.Read();
                        if (reader.Name == "managerstyle" && reader.NodeType == XmlNodeType.Element)
                        {
                            reader.Read();
                            string stylemana = reader.Value.ToString();

                            if (stylemana == "Office2007Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Blue;
                            if (stylemana == "Office2007Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Silver;
                            if (stylemana == "Office2007Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Black;
                            if (stylemana == "Windows7Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Windows7Blue;
                            if (stylemana == "Office2007VistaGlass")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007VistaGlass;
                            if (stylemana == "Office2010Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Silver;
                            if (stylemana == "Office2010Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Blue;
                            if (stylemana == "Office2010Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Black;
                        }
                    }
                }
            }
            reader.Close();
        }

        public void ConfigSetting()
        {
            ReadSetting();
            for (int i = 0; i < Controls[0].Controls[1].Controls[2].Controls.Count; i++)
            {
                if (Controls[0].Controls[1].Controls[2].Controls[i] is LabelX)
                {
                    Controls[0].Controls[1].Controls[2].Controls[i].Font = fontForAll;
                }
            }

            styleManager1 = managerStyle;
        }
       
        private void Students_Load(object sender, EventArgs e)
        {
            

        }

        public Student1()
        {
            InitializeComponent();
            Student_initial();
        }

        private void Student1_Load(object sender, EventArgs e)
        {
            flag = true;
            ConfigSetting();
            co = true;
            
        }

        private void btnXInsert_Click(object sender, EventArgs e)
        {
         // insert click
            pages.Text = "1";
       
            try
            {
                student_GetInfo();
                if (newstudent.AddNewStudent())
                {
                    labelItemStatus.Text = "Write DB successfully.";
                    // refresh datagrid
                    query = "SELECT * FROM studentinfo";
                    dataview.DataOnDataGridViewInitial(dgvExDanhSach , query, 2, -1, pages);
                    dataview.viewdata(dgvExDanhSach,pages);
                    initial_button();



                    btnXWriteTag.Enabled = true;
                    btnXInsert.Enabled = false;

                    txtTagID.Enabled = false;
                    txtXName.Enabled = false;
                    cmbExClass.Enabled = false;
                    cmbExDay.Enabled = false;
                    cmbExGender.Enabled = false;
                    cmbExMonth.Enabled = false;
                    txtXYear.Enabled = false;
                    txtXAccount.Enabled = false;
                }
                else
                    labelItemStatus.Text = "Write DB failed";
                newstudent.CloseConnect();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Input wrong. Please full all blanks.\n" + ex.Message, "Requirement");
            }
        
        }

        private void btnXWriteTag_Click(object sender, EventArgs e)
        {
          // tag write
        
            int size;
            try
            {
                rfid_reader.LogIn();
                size = connect.getdata(serial_buff);
                // ReadData from tag
                if (serial_buff[3] == 0x02 && size != 5000)
                {
                    rfid_reader.bt_write(newstudent.TagID,newstudent.Account);
                    connect.getdata(serial_buff);
                    if (serial_buff[3] == 0x00 && size != 5000)
                    {
                        labelItemStatus.Text = "Ghi vao the thanh cong !";
                        FormReset();
                    }
                    else
                        labelItemStatus.Text = "Ghi vao the that bai !";
                }
                else
                    labelItemStatus.Text = "Ghi vao the that bai !";
            }
            catch (Exception es)
            {
                MessageBox.Show("Loi khong ghi tag duoc: " + es.Message, "Loi");
            }
        
        }

        private void btnXExportExcel_Click(object sender, EventArgs e)
        {
            list = dataview.GetList();
            excel = new Services.ExcelInterface(list, columnName, 2, 2);
        }

        private void btnXUpdate_Click(object sender, EventArgs e)
        {
         // update account
            pages.Text = "1";
            DialogResult confirm = MessageBox.Show("Are you sure update: " + txtXName.Text + " ?", "Delete Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            try
                {
                    if (confirm == DialogResult.Yes)
                    {                
                        student_GetInfo();
                        if (newstudent.update_account(txtTagID.Text))
                        {
                            FormReset();
                            Student_initial();
                        }
                        labelItemStatus.Text = "Update " + txtXName.Text + " information succesfully";
                    }
                    else
                        labelItemStatus.Text = "Update " + txtXName.Text + " information failed";
                    dataview.viewdata(dgvExDanhSach, pages);

                    
                }
            catch (Exception ex)
            {
                MessageBox.Show("Input wrong. Please full all blanks.\n" + ex.Message, "Requirement");
            }
        
        }

        private void btnXDelete_Click(object sender, EventArgs e)
        {
         // delete account
            pages.Text = "1";
            
            DialogResult confirm = MessageBox.Show("Are you sure delete "+txtXName.Text+" ?", "Delete Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (confirm == DialogResult.Yes)
            {
                if (newstudent.delete_account(txtTagID.Text))
                {
                    FormReset();
                    Student_initial();
                }
            }
            dataview.viewdata(dgvExDanhSach, pages);
        
        }

        private void btnXReset_Click(object sender, EventArgs e)
        {
          //Form reset
        
            FormReset();
            Student_initial();
        

        }

        private void Student1_FormClosed(object sender, FormClosedEventArgs e)
        {
        Application.ExitThread();
            Application.Exit();
        }

        private void Student1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.ExitThread();
            Application.Exit();
        }

        private void Student1_Resize(object sender, EventArgs e)
        {
            int w = dgvExDanhSach.Size.Width;
            int widthC = ((int)w / dgvExDanhSach.Columns.Count);
            if (co == true)
            {
                for (int i = 0; i < dgvExDanhSach.Columns.Count; i++)
                {
                    dgvExDanhSach.Columns[i].Width = widthC;
                }
                    
          
            }
        }

        private void dgvExDanhSach_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
             // datagridview header click
       
            int row;
            DateTime dt;
            try
            {
                action = 3;

                txtTagID.Enabled = false;
                btnXInsert.Enabled = false;
                btnXWriteTag.Enabled = true;
                btnXDelete.Enabled = true;
                btnXUpdate.Enabled = true;

                row = e.RowIndex;
                
                txtTagID.Text = dgvExDanhSach.Rows[row].Cells[0].Value.ToString();
                txtXName.Text = dgvExDanhSach.Rows[row].Cells[1].Value.ToString();
                dt = Convert.ToDateTime(dgvExDanhSach.Rows[row].Cells[2].Value);
                cmbExDay.Text = dt.Day.ToString();
                cmbExMonth.Text = dt.Month.ToString();
                txtXYear.Text = dt.Year.ToString();
                cmbExGender.Text = dgvExDanhSach.Rows[row].Cells[3].Value.ToString();
                cmbExClass.Text = dgvExDanhSach.Rows[row].Cells[4].Value.ToString();
                txtXAccount.Text = dgvExDanhSach.Rows[row].Cells[5].Value.ToString();
                if (dgvExDanhSach.Rows[row].Cells[6].Value.ToString() != "")
                    cmbExLastTime.Text = dgvExDanhSach.Rows[row].Cells[6].Value.ToString();
                else
                    cmbExLastTime.Text = "NONE";

                student_GetInfo();
            }
            catch
            {
                row = 0;
            }
        
        }

      

      

        
    }
}
